package admin

import (
	"context"
	"strconv"
	"strings"

	"suci-go-zero/common/xerr"
	"suci-go-zero/internal/model"
	"suci-go-zero/internal/svc"
	"suci-go-zero/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpMenuLogic {
	return &UpMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpMenuLogic) UpMenu(req *types.RoleUpMenus) error {
	idArry := make([]string, 0)
	for _, id := range req.Menus {
		idArry = append(idArry, strconv.Itoa(id))
	}
	idsString := strings.Join(idArry, ",")

	role, err := l.svcCtx.Models.Role.FindOne(l.ctx, int64(req.Id))
	if err != nil && err != model.ErrNotFound {
		return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "")
	}

	if role == nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "")
	}
	role.Menus = idsString

	err = l.svcCtx.Models.Role.UpdateWithVersion(l.ctx, nil, role)

	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "")
	}

	return err
}
